package com.fjnu.shiro.service;

import java.util.Collection;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.jca.context.SpringContextResourceAdapter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fjnu.dao.IUserDao;
import com.fjnu.dao.common.DaoException;
import com.fjnu.dao.impl.UserDao;
import com.fjnu.entities.Role;
import com.fjnu.entities.User;
import com.fjnu.service.IUserService;
import com.fjnu.service.impl.UserService;

/**
 * 自定义Realm,进行数据源配置
 *
 *
 */

@Service
@Transactional(propagation=Propagation.REQUIRED)
public class MyRealm extends AuthorizingRealm{
    @Autowired
    private IUserService userService;  
//    @Autowired
 //   private IUserDao useDao;
/*
    public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
*/
	/**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录时输入的用户名  
        String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();
        //到数据库获取此用户
        //User user =new User();
		//user.setIdnumber(loginName);
        User user= userService.loginFindUnique(loginName);
        if(user!=null){
            //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）  
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            //用户的角色集合
            info.setRoles(user.getRolesName());
            //用户的角色对应的所有权限，如果只使用角色定义访问权限
            Collection<Role> roleList=user.getRoleList();
            for (Role role : roleList) {
                info.addStringPermissions(role.getPermissionsName());
            }
            return info;
        }
        return null;
    }

    /**
     * 获取身份验证相关信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        //UsernamePasswordToken对象用来存放提交的登录信息  
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
      //  System.out.println(userService);
        //查出是否有此用户 
       // User user= n//ew User();
        //user.setIdnumber(token.getUsername());
        String username =(String)token.getPrincipal();
        String password = String.valueOf(token.getPassword());
        User user= userService.loginFindUnique(username);
        //User user=new User();
        //user.setIdnumber("1");
        //user.setPassword("1");
        //System.out.println(user);
        if(user==null){
            //若存在，将此用户存放到登录认证info中  
//        	System.out.println("user"+user.getPassword());
        	throw new UnknownAccountException();
        }
       if(user.getPassword().equals(password)){
    	   SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
					username, password.toCharArray(), getName());
    	   Subject subject = SecurityUtils.getSubject();
    	   Session session = subject.getSession();
    	   session.setAttribute("subject",user);
    	   return info;
       }
       else if(!user.getPassword().equals(password)){
    	   throw new IncorrectCredentialsException();
       }
       return null;
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
}